// pages/search/search.js
import request from '../../utils/request'
let isSend = false 
Page({

  /**
   * 页面的初始数据
   */
  data: {
    placeholderContext: '',
    hotList: [], 
    searchContent: '', 
    searchList: [], 
    historyList:[] 
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getInitData()
    this.getHistoryList()
  },
  async getInitData () {
    const placeholderData = await request('/search/default')
    const hotListData = await request('/search/hot/detail')
    this.setData({
      placeholderContext: placeholderData.data.showKeyword,
      hotList: hotListData.data
    })
  },
  handlerSearchContent (event) {
    const searchContent = event.detail.value.trim() 
    this.setData({
      searchContent
    })
    if (isSend) { 
      return
    }
    isSend = true
    this.getSearchList()
    setTimeout(() => { 
      isSend = false
    },200)
  },
  async getSearchList () {
    const { searchContent,historyList } = this.data
    if (!searchContent) {
      this.setData({
        searchList: [] 
      })
      return
    }
    
    const searchListData = await request('/search', { keywords: searchContent, limit: 10 })
    this.setData({
      searchList: searchListData.result.songs
    })
    if (historyList.indexOf(searchContent) !== -1) { 
      historyList.splice(historyList.indexOf(searchContent),1)
    }
    historyList.unshift(searchContent)
    this.setData({
      historyList
    })
    wx.setStorageSync('historyList',historyList)
  },
  getHistoryList () { 
    let historyList = wx.getStorageSync('historyList')
    if (historyList) { 
      this.setData({
        historyList
      })
    }
  },
  deleteHistoryList () { 
    wx.showModal({
      title: '删除提示',
      content: '您确定要删除历史记录吗?',
      success :(res)=> {
        if (res.confirm) {
          this.setData({
            historyList:[] // 清空数组
          })
          // 删除缓存
          wx.removeStorageSync('historyList')
        } 
      }
    })
  },
  clear () { 
    this.setData({
      searchContent:'',
      searchList:[]
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})